package com.gxpt.app.view;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.bean.confirmcart_bean;
import com.gxpt.app.bean.createorder2_bean;
import com.gxpt.app.bean.createorder_bean;
import com.gxpt.app.bean.getallcategory_bean;
import com.gxpt.app.bean.normal;
import com.utils.ScreenUtils;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.utils.picasso.PicassoUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_shopping_confirm)
public class Activity_shopping_confirm extends BaseActivity {

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.toSelcontent)
    LinearLayout toSelcontent;

    @ViewInject(R.id.toSelCoupon)
    RelativeLayout toSelCoupon;

    @ViewInject(R.id.toInvoice)
    RelativeLayout toInvoice;


    @ViewInject(R.id.goods_list_layout)
    LinearLayout goods_list_layout;

    @ViewInject(R.id.ts)
    TextView ts;

    @ViewInject(R.id.info1)
    LinearLayout info1;

    @ViewInject(R.id.info2)
    LinearLayout info2;

    @ViewInject(R.id.txt_fapiao)
    TextView txt_fapiao;


    @ViewInject(R.id.txt_total_price)
    TextView txt_total_price;

    @ViewInject(R.id.txt_spjine)
    TextView txt_spjine;

    @ViewInject(R.id.txt_zkjine)
    TextView txt_zkjine;

    @ViewInject(R.id.txt_quzhekou)
    TextView txt_quzhekou;

    @ViewInject(R.id.txt_yunfei)
    TextView txt_yunfei;

    @ViewInject(R.id.switch1)
    Switch switch1;


///////////////////////////收货
    @ViewInject(R.id.txt_shouhuoren)
    TextView txt_shouhuoren;

    @ViewInject(R.id.txt_phone)
    TextView txt_phone;

    @ViewInject(R.id.txt_shouhuodizhi)
    TextView txt_shouhuodizhi;

    //积分
    @ViewInject(R.id.txt_jifen)
    TextView txt_jifen;

    //抵扣
    @ViewInject(R.id.txt_dikou)
    TextView txt_dikou;

    //优惠券
    @ViewInject(R.id.txt_youhuiquan)
    TextView txt_youhuiquan;

    @ViewInject(R.id.toPay)
    TextView toPay;

    confirmcart_bean.confirmcart cartinfo;
    int address_id =0;//收货地址ID


    int pic_view_width = 0;
    int pic_view_hight = 0;

    List<getallcategory_bean.getallcategory> type = null;
    getallcategory_bean toData = null;

    String[]  titles = null;
    String[]  ids = null;

    JSONArray jy;
    JSONArray data = new JSONArray();

    int invoice_type = 0 ;//发票类型 0.个人 1.企业
    int invoice_desc = 0 ;// 0明细 1耗材 2办公用品3 电脑配件

    String invoice_title;
    String invoice_phone;
    String invoice_email;

    int has_invoice = 0 ;//0 不开 1 开具


    float zhekou =0;
    float zongjia =0;
    int score = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        x.view().inject(this);

        String DATA = getIntent().getStringExtra("DATA");

        try {
            jy = new JSONArray(DATA);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.i("DATA = "+DATA.toString());
        initView();
        initData();
    }

    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){
        if(messageEvent.getMessageType() ==Constant.ACTION_address_sel ){

            txt_shouhuoren.setText(""+messageEvent.getMessage());
            txt_phone.setText(""+messageEvent.getId1());
            txt_shouhuodizhi.setText(""+messageEvent.getId2());

            address_id = messageEvent.getIndex();

            info1.setVisibility(View.VISIBLE);
            info2.setVisibility(View.VISIBLE);
            ts.setVisibility(View.GONE);

        }else if(messageEvent.getMessageType() ==Constant.ACTION_invoice_info2){
            invoice_type = messageEvent.getInt_1();
            invoice_desc = messageEvent.getInt_2();
            has_invoice  = messageEvent.getInt_3();
            invoice_title = messageEvent.getStr_1();
            invoice_phone = messageEvent.getStr_2();
            invoice_email = messageEvent.getStr_3();

            if(has_invoice ==0){
                txt_fapiao.setText(""+getResources().getString(R.string.txt_bukaifapiao));
            }else{
                if(invoice_type == 0){
                    txt_fapiao.setText(""+getResources().getString(R.string.txt_geren));
                }else{
                    txt_fapiao.setText(""+getResources().getString(R.string.txt_danwei));
                }

            }

        }
    }


    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_shouhuoxinxiqueren));
        int Sviewwidth  = ScreenUtils.getScreenWidth(context);//
        pic_view_width  = Sviewwidth / 5;
        pic_view_hight  = pic_view_width/4*3;

        info1.setVisibility(View.GONE);
        info2.setVisibility(View.GONE);

        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    txt_spjine.setText(getString(R.string.txt_azongjia,""+zongjia));
                    txt_zkjine.setText("-"+getString(R.string.txt_azongjia,""+zhekou));


                    txt_total_price.setText(getString(R.string.txt_azongjia,""+(zongjia - zhekou)));
                }else{
                    txt_spjine.setText(getString(R.string.txt_azongjia,""+zongjia));
                    txt_zkjine.setText("-"+getString(R.string.txt_azongjia,"0.00"));

                    txt_total_price.setText(getString(R.string.txt_azongjia,""+zongjia));
                }
            }
        });
    }

    @Override
    public void initData() {
        toNet_confirmcart();
    }


    private void init_List_main_type(){


        goods_list_layout.removeAllViews();

        zhekou = Float.parseFloat(cartinfo.score_deduction);//折扣
        zongjia= Float.parseFloat(cartinfo.total_price);//总价
        score  = Integer.parseInt(cartinfo.score);


        txt_jifen.setText(getString(R.string.txt_fen_m,cartinfo.score));
        txt_dikou.setText(getString(R.string.txt_dikou_m,cartinfo.score_deduction));

        txt_youhuiquan.setText(getString(R.string.txt_quan_m,""+cartinfo.coupon.size()));

        txt_spjine.setText(getString(R.string.txt_azongjia,cartinfo.total_price));
        txt_zkjine.setText("-"+getString(R.string.txt_azongjia,"0.00"));
        txt_quzhekou.setText("-"+getString(R.string.txt_azongjia,"0.00"));
        txt_yunfei.setText("+"+getString(R.string.txt_azongjia,"0.00"));

        txt_total_price.setText(getString(R.string.txt_azongjia,cartinfo.total_price));



        for (int a = 0; a < cartinfo.cartinfo.size(); a++) {
            goods_list_layout.addView(creatListItemView(a));
        }
    }

    private View creatListItemView(int id) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_shopping_confirm_list, null);
        TextView txt_shop_name = (TextView)convertView.findViewById(R.id.txt_shop_name);
        txt_shop_name.setText(cartinfo.cartinfo.get(id).shop_name);

        TextView txt_shop_id = (TextView)convertView.findViewById(R.id.txt_shop_id);
        Logger.i("cartinfo.cartinfo.get(id).shop_id = "+cartinfo.cartinfo.get(id).shop_id);
        txt_shop_id.setText(cartinfo.cartinfo.get(id).shop_id);

        LinearLayout layout_sub = (LinearLayout)convertView.findViewById(R.id.layout_sub);



        if(cartinfo.cartinfo.get(id).goods != null ){
            if(cartinfo.cartinfo.get(id).goods.size()>0){
                for (int a = 0; a < cartinfo.cartinfo.get(id).goods.size(); a++) {
                    layout_sub.addView(creat_sub_goods_views(cartinfo.cartinfo.get(id).goods.get(a),a));
                }
            }
        }

        return convertView;
    }

    private View creat_sub_goods_views(confirmcart_bean.confirmcart.cartinfo_l.goods_l gs,int index) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_item_shopping_confirm_list, null);

        Logger.i("gs.sku_id = "+gs.sku_id);

        TextView txt_gone_goods_id = (TextView)convertView.findViewById(R.id.txt_gone_goods_id);
        txt_gone_goods_id.setText(gs.goods_id);
        TextView txt_gone_sku_id = (TextView)convertView.findViewById(R.id.txt_gone_sku_id);
        txt_gone_sku_id.setText(gs.sku_id);
        TextView txt_gone_goods_num = (TextView)convertView.findViewById(R.id.txt_gone_goods_num);
        txt_gone_goods_num.setText(gs.goods_num);



        TextView txt_goods_name = (TextView)convertView.findViewById(R.id.txt_goods_name);
        txt_goods_name.setText(gs.goods_name);

        TextView txt_sku_name = (TextView)convertView.findViewById(R.id.txt_sku_name);
        txt_sku_name.setText(gs.sku_name);

        TextView txt_sell_price = (TextView)convertView.findViewById(R.id.txt_sell_price);
        txt_sell_price.setText(gs.sell_price);

        TextView txt_buy_num = (TextView)convertView.findViewById(R.id.txt_buy_num);
        txt_buy_num.setText("x "+gs.goods_num);


        ImageView img_thumb= (ImageView)convertView.findViewById(R.id.img_thumb);
        if(gs.thumb.isEmpty()){
            PicassoUtils.Picasso_displayImage(context,R.mipmap.ic_launcher,pic_view_width,pic_view_hight,img_thumb);
        }else{
            PicassoUtils.Picasso_displayImage(context,Constant.IP+"/"+gs.thumb,pic_view_width,pic_view_hight,img_thumb);
        }
        return convertView;
    }


    @Event(value={R.id.toback,R.id.toSelcontent,R.id.toSelCoupon,R.id.toInvoice,R.id.toPay})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
            case R.id.toSelcontent:
                jumpActivity(Activity_center_storeaddress_list.class,false);
                break;
            case R.id.toSelCoupon:
                jumpActivity(Activity_center_mycoupon_list.class,false);
                break;
            case R.id.toInvoice:
                jumpActivity(Activity_invoice.class,false);
                break;
            case R.id.toPay:
                if(address_id == 0 ){
                    T.show(context,getResources().getString(R.string.alert_not_address),0);
                }else{
                    try {
                        for(int a=0;a<goods_list_layout.getChildCount();a++){
                            JSONObject jsoncar = new JSONObject();

                            LinearLayout shopes_layout = (LinearLayout) goods_list_layout.getChildAt(a);
                            for(int b=0;b<shopes_layout.getChildCount();b++) {

                                View v = shopes_layout.getChildAt(b);
                                if (v.getId() == R.id.txt_shop_id){
                                    TextView shop_id = (TextView) shopes_layout.findViewById(R.id.txt_shop_id);
                                    jsoncar.put("shop_id", "" +shop_id.getText());
                                }
                                if (v.getId() == R.id.txt_shop_id){
                                    EditText edit_message = (EditText) shopes_layout.findViewById(R.id.edit_message);
                                    jsoncar.put("message", "" +edit_message.getText());
                                }

                                JSONArray goods = new JSONArray();
                                if(v.getId() == R.id.layout_sub){

                                    LinearLayout layout_sub = (LinearLayout) shopes_layout.findViewById(R.id.layout_sub);
                                    for(int c=0; c < layout_sub.getChildCount();c++) {

                                        JSONObject jb1 = new JSONObject();

                                        LinearLayout item_item_goods = (LinearLayout) layout_sub.getChildAt(c);
                                        for(int d=0; d < item_item_goods.getChildCount();d++) {

                                            View vc = item_item_goods.getChildAt(d);

                                            if(vc.getId() == R.id.txt_gone_goods_id){
                                                TextView txt_gone_goods_id = (TextView) item_item_goods.findViewById(R.id.txt_gone_goods_id);
                                                jb1.put("goods_id", "" +txt_gone_goods_id.getText());
                                            }
                                            if(vc.getId() == R.id.txt_gone_sku_id){
                                                TextView txt_gone_sku_id = (TextView) item_item_goods.findViewById(R.id.txt_gone_sku_id);
                                                jb1.put("sku_id", "" +txt_gone_sku_id.getText());

                                            }
                                            if(vc.getId() == R.id.txt_gone_goods_num){
                                                TextView txt_gone_goods_num = (TextView) item_item_goods.findViewById(R.id.txt_gone_goods_num);
                                                jb1.put("goods_num", "" +txt_gone_goods_num.getText());
                                            }

                                        }
                                        goods.put(jb1);

                                    }
                                    jsoncar.put("goods",goods);
                                }

                            }

                            data.put(jsoncar);
                        }

                        toNet_createorder();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                break;
        }
    }



    public void Dialog_zhaobiaomodel(List<createorder2_bean.createorder2> xjxgoods){
        final Dialog dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_goods, null);
        dialog.setContentView(view);

        LinearLayout lists = (LinearLayout)view.findViewById(R.id.goods_list_layout);

        for(int a=0;a<xjxgoods.size();a++){
            lists.addView(creatGoodsView(xjxgoods.get(a).goods_id));
        }


        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }


    private View creatGoodsView(int id) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_goods_xiajia_list, null);
        TextView list_title = (TextView)convertView.findViewById(R.id.list_title);
        list_title.setText("商品连接["+id+"]");

        TextView list_id = (TextView)convertView.findViewById(R.id.list_id);
        list_id.setText(""+id);

        convertView.setTag(id);

        convertView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Bundle b = new Bundle();
                b.putString("ID",""+v.getTag());
                Intent gonew =new Intent();
                gonew.setClass(context,Activity_webview.class);
                gonew.putExtra("DATA",b);
                startActivity(gonew);
            }
        });

        return convertView;
    }


















    //////NET DO
    StringCallback do_confirmcart = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(s);
            try{
                confirmcart_bean data = new Gson().fromJson(s, confirmcart_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        cartinfo = data.data;
                        init_List_main_type();




//                            toData = data;
//                            type = data.data;
//
//                                //main
////                                init_List_main_type();
//                                if(data.data.get(0).children !=null){
//                                    if(data.data.get(0).children.size()>0){
//                                        //sub
////                                        init_List_sub_type(0);
//                                    }
//                                }

                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

    /////NET
    private void toNet_confirmcart(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shopcart");
            jsonBody.put("serviceName",          "confirmcart");

            jsonBody.put("member_id",          AppUtils.get_user_id(context));
            jsonBody.put("data",                jy);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Logger.i(jsonBody.toString()+"  ["+Constant.URL_confirmcart+"]");
        HttpUtils.http_post_string(Constant.URL_confirmcart,jsonBody.toString(),do_confirmcart);
    }

    /////NET
    private void toNet_createorder(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "shoporder");
            jsonBody.put("serviceName",          "createorder");

            jsonBody.put("member_id",          AppUtils.get_user_id(context));
            jsonBody.put("has_invoice",        has_invoice);
            jsonBody.put("invoice_title",      invoice_title);
            jsonBody.put("invoice_type",       invoice_type);
            jsonBody.put("invoice_desc",       invoice_desc);
            jsonBody.put("invoice_phone",      invoice_phone);
            jsonBody.put("invoice_email",      invoice_email);
            jsonBody.put("score",              score);
            jsonBody.put("address_id",         address_id);

            jsonBody.put("data",                data);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Logger.i(jsonBody.toString()+"  ["+Constant.URL_createorder+"]");
        HttpUtils.http_post_string(Constant.URL_createorder,jsonBody.toString(),do_createorder);
    }


    StringCallback do_createorder = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e(s);/
            try{
                normal data = new Gson().fromJson(s, normal.class);

                switch(data.state){
                    case 1://生成成功
                        createorder_bean data1 = new Gson().fromJson(s, createorder_bean.class);
                        if(data1.data != null){
                            T.show(context,getResources().getString(R.string.alert_ok_1),0);
                            Bundle b = new Bundle();
                            b.putString("order_id",    data1.data.order_id);
                            b.putString("total_price", data1.data.total_price);
                            jumpActivity(Activity_pay_shopping.class,b,true);
                        }
                        break;
                    case 5001:
                        createorder2_bean data2 = new Gson().fromJson(s, createorder2_bean.class);
                        Dialog_zhaobiaomodel(data2.data);
                        break;
                    case 5002:
                        T.show(context,data.msg,0);
                        break;
                    case 5005:
                        T.show(context,data.msg,0);
                        break;
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
}
